<?php

namespace app\admin\controller\chase;

use app\api\model\Qrcode;
use app\common\controller\Backend;
use app\admin\model\chase\UserCoupon as UserCouponModel;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 用户优惠券管理
 *
 * @icon fa fa-circle-o
 */
class UserCoupon extends Backend
{
    
    /**
     * UserCoupon模型对象
     * @var \app\admin\model\chase\UserCoupon
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\chase\UserCoupon;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("wayList", $this->model->getWayList());
        $this->assign('coupons', \app\admin\model\chase\Coupon::getCoupons());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with('user')
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with('user')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            array_walk($list, function (&$val) {
                if ($val['type'] == 2 && $val['discount_amount'] > 0) {
                    $val['discount_amount'] = $val['discount_amount'] / 1 . '折';
                }
            });
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 核销优惠码
     */
    public function code()
    {
        $code = $this->request->post('code');
        $user_coupon= UserCouponModel::getByCode(strtoupper($code));
        if (!$user_coupon) {
            $this->error('用户优惠券不存在');
        }
        if ($user_coupon->status != 1) {
            $this->error('优惠券已过期或已使用');
        }
        $user_coupon->status = 2;
        $result = $user_coupon->save();
        $result ? $this->success('核销成功') : $this->error('核销失败');
    }

    /**
     * 核销优惠券
     */
    public function check()
    {
        $id = $this->request->post('id');
        $user_coupon = UserCouponModel::find($id);
        if (!$user_coupon) {
            $this->error('用户优惠券不存在');
        }
        if ($user_coupon->status != 1) {
            $this->error('优惠券已过期或已使用');
        }
        $user_coupon->status = 2;
        $result = $user_coupon->save();
        $result ? $this->success('核销成功') : $this->error('核销失败');
    }

    /**
     * 查看用户优惠券
     */
    public function coupon($user_id)
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->with('user')
                ->where('user_id', $user_id)
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with('user')
                ->where('user_id', $user_id)
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            array_walk($list, function (&$val) {
                if ($val['type'] == 2 && $val['discount_amount'] > 0) {
                    $val['discount_amount'] = $val['discount_amount'] / 1 . '折';
                }
            });
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        $this->assign('user_id', $user_id);
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function create($user_id)
    {;
        if ($this->request->isPost()) {
            $coupon_id = $this->request->post('coupon_id');
            if (!$coupon_id) {
                $this->error('优惠券不能为空');
            }
            $coupon = \app\admin\model\chase\Coupon::find($coupon_id);
            if (!$coupon) {
                $this->error('优惠券不存在');
            }
            //生成优惠码
            $code = strtoupper(substr(md5(date("YmdHis").mt_rand(10000, 99999).$user_id), 8, 16));
            //生成二维码
            $qrcode = Qrcode::createQrcode('youhuima'. $code);

            $result = UserCouponModel::create([
                'user_id' => $user_id,
                'coupon_id' => $coupon->id,
                'service_id' => $coupon->service_id,
                'code' => $code,
                'qrcode' => $qrcode,
                'coupon_name' => $coupon->title,
                'discount_amount' => $coupon->discount_amount,
                'need_amount' => $coupon->need_amount,
                'start_time' => $coupon->expired_type == 2 ? time() : $coupon->start_time,
                'end_time' => $coupon->expired_type == 2 ? time() + $coupon->expiry_date * 86400 : $coupon->end_time,
                'type' => $coupon->discount_type,
                'way' => 4,
                'coupon_type' => $coupon->type,
                'createtime' => time()
            ]);
            $result ? $this->success('添加成功') : $this->error('添加失败');
        }
        return $this->view->fetch();
    }

}
